"use strict";
cc._RF.push(module, 'fc9e8Z//n9Md4LkS47rLz6T', 'Http');
// scripts/utils/Http.js

"use strict";

var URL = "http://127.0.0.1:2018/"; //连接地址


var md5 = require("MD5");
var HttpClient = cc.Class({
    extends: cc.Component,
    statics: {
        version: "1.0.0",
        master_url: URL,
        url: URL,
        reConnectCount: 2, //重连次数
        /*
        功能：发送消息请求
        参数说明
        path：请求的协议地址
        data: 请求参数
        handler: 绑定回调
        sendType: 发送类型，默认POST
        outTime: 超时时间
        extraUrl：自定义需要连接的地址，默认URL地址
        */
        sendRequest: function sendRequest(path, data, handler, sendType, outTime, extraUrl) {
            cc.log("http sendRequest");
            var xhr = cc.loader.getXMLHttpRequest();
            if (outTime == null) {
                xhr.timeout = 4000;
            } else {
                xhr.timeout = outTime;
            }
            if (sendType == null) {
                sendType = "POST";
            }
            if (extraUrl == null) {
                extraUrl = HttpClient.url;
            }

            //结构体------------------------------------------------
            var dataObj = new Object();
            dataObj = JSON.parse(JSON.stringify(data));
            var newTime = new Date().getTime();
            var timeUtc = newTime.toString();

            dataObj["TimeStamp"] = timeUtc;
            dataObj["Secret"] = "123456789";
            var dataStr = "?";
            for (var k in dataObj) {
                if (dataStr != "?") {
                    dataStr += "&";
                }
                dataStr += k + "=" + dataObj[k];
                if (dataStr === "?") dataStr = "";
            }

            var dataMd5 = md5.hex_md5(dataStr);
            var dataTemp = new Object();
            dataTemp = JSON.parse(JSON.stringify(data));
            dataTemp["UnixTime"] = timeUtc;
            dataTemp["Digest"] = dataMd5;

            //----------------  --------------------------------------

            if (sendType == "POST") {
                var str = "";
                for (var k in dataTemp) {
                    if (str != "") {
                        str += "&";
                    }
                    str += k + "=" + dataTemp[k];
                }
                var requestURL = extraUrl + path;
                xhr.open(sendType, requestURL, true);
                //cc.log("http POST str:" + str);
                //  cc.log("http POST RequestURL:" + requestURL);
            } else if (sendType == "GET") {
                var str = "?";
                for (var k in dataTemp) {
                    if (str != "?") {
                        str += "&";
                    }
                    str += k + "=" + dataTemp[k];
                }
                if (str === "?") str = "";
                var requestURL = extraUrl + path + str;
                xhr.open(sendType, requestURL, true);
                //   cc.log("http GET RequestURL:" + requestURL);
            } else if (sendType == "PUT") {
                var str = "";
                for (var k in dataTemp) {
                    if (str != "") {
                        str += "&";
                    }
                    str += k + "=" + dataTemp[k];
                }
                var requestURL = extraUrl + path;
                xhr.open(sendType, requestURL, true);

                //cc.log("http PUT str:" + str);
                //   cc.log("http PUT RequestURL:" + requestURL);
            }

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
                    //|| (xhr.status === 0)
                    try {
                        var ret = JSON.parse(xhr.responseText);
                        cc.info("http responseText:" + xhr.responseText);
                        var obj = eval('(' + ret + ')');
                        //cc.info("http ret:"+ ret);

                        if (handler !== null) {
                            handler(obj);
                        }
                    } catch (e) {
                        cc.error("http error:" + e || "e is not define");
                        xhr.abort();
                        xhr = null;
                        var data = {
                            Code: -1,
                            Msg: "连接失败"
                        };
                        handler(data);
                    } finally {}
                }
            };

            try {
                xhr.send(str);
            } catch (error) {
                cc.error("http error:" + error);
                xhr.abort();
                xhr = null;
                var data = {
                    Code: -1,
                    Msg: "发送请求失败"
                };
                handler(data);
                return null;
            }
            return xhr;
        },

        /*
        功能：发送消息请求扩展，自动检测重连 reconnectcount重连次数
        参数说明
        path：请求的协议地址
        data: 请求参数
        handler: 绑定回调
        sendType: 发送类型，默认POST
        outTime: 超时时间
        extraUrl：自定义需要连接的地址，默认URL地址
        */
        sendRequestRet: function sendRequestRet(path, data, handler, sendType, outTime, extraUrl) {
            cc.log("http sendRequestRet");
            var self = this;
            var xhr = null;
            var pathTemp = path;
            var dataTemp = data;
            var sendTypeTemp = sendType;
            var outTimeTemp = outTime == null || outTime == undefined ? null : outTime;
            var handlerTemp = handler;

            var count = 0;
            var fnRequest = function fnRequest() {
                xhr = self.sendRequest(pathTemp, dataTemp, function (ret) {
                    if (ret.Code == -1) {
                        count++;
                        cc.log("http reconnect " + count);
                        if (count >= self.reConnectCount) {
                            handlerTemp(ret);
                        } else fnRequest();
                    } else {
                        handlerTemp(ret);
                    }
                }, sendTypeTemp, outTimeTemp);
            };
            fnRequest();
        },

        /*
        功能：同步发送消息请求 暂未使用
        */
        sendSynchroRequest: function sendSynchroRequest(path, data, sendType) {
            cc.info("http sendSynchroRequest");
            var xhr = cc.loader.getXMLHttpRequest();
            if (sendType == null) {
                sendType = "POST";
            }

            if (sendType == "POST") {
                var str = "";
                for (var k in data) {
                    if (str != "") {
                        str += "&";
                    }
                    str += k + "=" + data[k];
                }
                var requestURL = HttpClient.url + path;
                xhr.open(sendType, requestURL, false);

                // cc.log("http POST str:" + str);
                xhr.send(str);
                cc.log("http POST RequestURL:" + requestURL);
            } else if (sendType == "GET") {
                var str = "?";
                for (var k in data) {
                    if (str != "?") {
                        str += "&";
                    }
                    str += k + "=" + data[k];
                }
                if (str === "?") str = "";
                var requestURL = HttpClient.master_url + path + str;
                xhr.open(sendType, requestURL, false);
                xhr.send();
                cc.log("http GET RequestURL:" + requestURL);
            } else if (sendType == "PUT") {
                var str = "";
                for (var k in data) {
                    if (str != "") {
                        str += "&";
                    }
                    str += k + "=" + data[k];
                }
                var requestURL = HttpClient.master_url + path;
                xhr.open(sendType, requestURL, false);
                //cc.log("http PUT str:" + str);
                xhr.send(str);
                cc.log("http PUT RequestURL:" + requestURL);
            }
            var result = xhr.status;
            //OK
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300 || xhr.status === 0)) {
                cc.info("http res(" + xhr.responseText.length + "):" + xhr.responseText);
                try {
                    var ret = JSON.parse(xhr.responseText);
                    var obj = eval('(' + ret + ')');
                    xhr = null;
                    return obj;
                } catch (e) {} finally {}
            }
            xhr = null;
            return null;
        }

    }
});

cc._RF.pop();